package com.sixuan.rabbitmqprovider;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;


/**
 * RabbitMq 入门Provider  Hello World!
 * Created by LENOVO on 2020-7-8 15:10
 *
 * @author LENOVO
 */
public class NormalProvider {
    private static final String rabbitMqHost = "47.97.195.191";
    private static final int rabbitMqPort = 5672;
    private static final String username = "guest";
    private static final String password = "guest";

    private static final String QUEUE_NAME = "helloWorld";


    public static void main(String[] args) {

        //通过连接工厂创建和mq的连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(rabbitMqHost);
        connectionFactory.setPort(rabbitMqPort);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        //设置虚拟机(一个虚拟机可以当做一个独立的rabbitmq应用，虚拟机之间是隔离的)
        connectionFactory.setVirtualHost("/");

        Connection connection = null;
        Channel channel = null;
        try {
            //建立新连接
            connection = connectionFactory.newConnection();
            //创建会话通道，生产者和mq服务所有的通信都在channel中进行
            channel = connection.createChannel();

            //声明一个队列：如果队列在mq中不存在，则创建一个
            //参数：String queue, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments
            /**
             *参数明细
             * 1.String queue 队列名称
             * 2.boolean durable 是否持久化
             * 3.boolean exclusive 是否独占连接，对接只允许在该连接中访问，如果关闭队列，则自动删除
             * 4.boolean autoDelete    是否自动删除 ，队列不在使用，则自动删除
             *                      如果将exclusive和autoDelete设置true，可用于临时队列的创建。
             * 5.Map<String, Object> arguments  参数，可以设置一个队列的扩展参数，如队列生存时间等，官方提供了许多扩展参数
             */
            channel.queueDeclare(QUEUE_NAME, true, false, false, null);

            //发动消息basicPublish
            //参数：String exchange, String routingKey, boolean mandatory, boolean immediate, BasicProperties props, byte[] body
            /**
             *参数明细
             * 1.String exchange 交换机名称，如果不指定，则使用默认的交换机
             * 2.String routingKey 路由key，交换机根据路由key来讲消息转发到指定的队列
             * 3.boolean mandatory
             * 4.boolean immediate
             * 5.BasicProperties props  消息属性
             * 6.byte[] body   消息内容
             */
            String message = "Hello World!";
            channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("Send to consumer finished !");
            try {
                channel.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}
